package com.shell.arc_scale_view

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.app.DownloadManager
import android.app.DownloadManager.Request
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.util.Log
import androidx.annotation.RequiresApi
import java.io.File
import java.net.URLDecoder

class DownloadUtil(private val context: Context) {

    private var listener: DownloadListener?=null

    interface DownloadListener {
        fun onProgressUpdate(progress: Int)
        fun onDownloadComplete(fileUri: String)
        fun onError(error: String)
    }

    private var downloadId: Long = -1

    private val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

    private val downloadReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            if (id == downloadId) {
                val downloadQuery = DownloadManager.Query().setFilterById(downloadId)
                val cursor = downloadManager.query(downloadQuery)
                if (cursor.moveToFirst()) {
                    val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                    when (status) {
                        DownloadManager.STATUS_RUNNING -> {
                            val totalBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                            val downloadedBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                            val progress = (downloadedBytes * 100f / totalBytes).toInt()
                            listener?.onProgressUpdate(progress)
                        }
                        DownloadManager.STATUS_SUCCESSFUL -> {

                            val fileUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
                            val filePath = fileUri.replace("file://", "")
                            // 文件路径是 fileUri    fileUri:content://downloads/all_downloads/12
                            println("fileUri:$filePath")
                            listener?.onDownloadComplete(filePath)
                            context?.unregisterReceiver(this)
                        }
                        DownloadManager.STATUS_FAILED -> {
                            listener?.onError("Download failed")
                            context?.unregisterReceiver(this)
                        }
                    }
                }
            }
        }
    }

    fun downloadAPK(url: String, mListener: DownloadListener?=null) {
//        val fileName = "myapk.apk"
        val fileName = URLDecoder.decode(url.substringAfterLast("/"), "UTF-8")
        listener = mListener
        // Check if the file already exists
        val fileNameTmp = "/storage/emulated/0/Documents/" + fileName
        if (fileExists(fileNameTmp)) {
            listener?.onDownloadComplete(fileNameTmp)
            Log.d("Fire", "downloadAPK: 文件已经存在")
            return
        }

        val uri = Uri.parse(url)
        val request = Request(uri)
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOCUMENTS, File.separator+fileName)
        request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)//在通知栏可见
        request.setTitle("软件更新")
        request.setDescription("下载中")
        request.setVisibleInDownloadsUi(true)

        downloadId = downloadManager.enqueue(request)

        // Register the broadcast receiver for download updates
        context.registerReceiver(downloadReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
    }

    private fun fileExists(fileName: String): Boolean {
        val file = File(fileName)
        return file.exists()
    }
}